from douban.list_thread import timer
from douban.list_tag import tags_type
from douban.detail_thread import detail
from douban.mongo import db
import time


class douban:
    def __init__(self):
        self.tags = []

    def get_tag(self):
        tag_list = tags_type()
        tag_list.start()
        tag_list.join()
        if tag_list.get_data():
            self.tags.extend(tag_list.get_data())
        return self.tags

    def run(self, tags_list):
        li = []
        for tag in tags_list:
            # if tag == '最新' or tag == '豆瓣高分':
            #     continue
            time1 = timer(tag, 0, 500)
            time1.start()
            time1.join()
            if time1.get_data():
                li.extend(time1.get_data())
            index = 0
            while index < len(li):
                time.sleep(5)
                d1 = detail(li[index]['url'])
                d1.start()
                d1.join()
                if d1.get_detail():
                    self.insert_db(d1.get_detail())
                index += 1
        li.clear()

    def insert_dbs(self, data):
        client = db().getClient()
        douban = client.douban
        movie = douban.movie
        for item in data:
            count = movie.find({"title": item['title']}).count()
            print(count)
            if count == 0:
                movie.insert(item)

    def insert_db(self, data):
        client = db().getClient()
        douban = client.douban
        movie = douban.movie
        count = movie.find({"title": data['title']}).count()
        print(count)
        if count == 0:
            movie.insert(data)
        else:
            movie.update({"title": data['title']}, {'$set': data})
